package cn.wj.school.app.net.client;

import cn.wj.school.app.net.client.handler.ClientReConnection;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.HashedWheelTimer;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: yueding
 * @Description: 客户端
 * @Date: Created in 20:23 2018/12/27
 * @Modified By: yueding Copyright(c) cai-inc.com
 */
@Slf4j
public class ClientNet {

    protected final HashedWheelTimer timer = new HashedWheelTimer();

    /**
     * 端口默认7878
     */
    private int port = 7878;
    private String host;

    private Bootstrap boot;


    public ClientNet(String host, Integer port) {
        this.host = host;
        if (port != null) {
            this.port = port;
        }
        try {
            start();
        }catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void start() throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();

        boot = new Bootstrap();
        boot.group(group).channel(NioSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO));

        final ClientReConnection watchdog = new ClientReConnection(boot, timer, port, host, true);

        ChannelFuture future;
        // 进行连接
        synchronized (boot) {
            boot.handler(new ChannelInitializer() {

                // 初始化channel
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(watchdog.handlers());
                }
            });

            future = boot.connect(host, port);
            log.info("============学生客户端启动成功!==========");
        }

        // 以下代码在synchronized同步块外面是安全的
        future.sync();
    }
}
